'use client';

import { useState, useRef, useEffect } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Modal, message, Select } from 'antd';
import {
  ProTable,
  ProColumns,
  ActionType,
  ProForm,
  ProFormText,
  ProFormSelect,
} from '@ant-design/pro-components';
import { Category, Menu } from '@prisma/client';
import { getCategoryPage, createCategory, updateCategory, deleteCategory } from '@/apis/admin/category';
import { getMenuList } from '@/apis/admin/menu';

const CategoryPage = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingCategory, setEditingCategory] = useState<Category | null>(null);
  const [menus, setMenus] = useState<Menu[]>([]);
  const actionRef = useRef<ActionType>(null);

  useEffect(() => {
    getMenuList().then((res) => {
      setMenus(res as any);
    });
  }, []);

  const handleCreate = () => {
    setEditingCategory(null);
    setIsModalVisible(true);
  };

  const handleUpdate = (record: Category) => {
    setEditingCategory(record);
    setIsModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteCategory(id);
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleFinish = async (values: any) => {
    try {
      if (editingCategory) {
        await updateCategory({ ...editingCategory, ...values });
        message.success('更新成功');
      } else {
        await createCategory(values);
        message.success('创建成功');
      }
      setIsModalVisible(false);
      actionRef.current?.reload();
      return true;
    } catch (error) {
      message.error(editingCategory ? '更新失败' : '创建失败');
      return false;
    }
  };

  const columns: ProColumns<Category & { menu: { name: string } }>[] = [
    { title: '分类名称', dataIndex: 'name', key: 'name' },
    {
      title: '所属菜单',
      dataIndex: ['menu', 'name'],
      key: 'menuName',
      search: false,
    },
    {
      title: '操作',
      key: 'action',
      search: false,
      render: (_, record) => [
        <a key="edit" onClick={() => handleUpdate(record)}>
          编辑
        </a>,
        <Button type='text' danger key="delete"  onClick={() => handleDelete(record.id)}>
          删除
        </Button>,
      ],
    },
  ];

  return (
    <>
      <ProTable<(Category & { menu: { name: string } })>
        columns={columns}
        actionRef={actionRef}
        request={async (params) => {
          const { current, pageSize, ...rest } = params;
          const res = await getCategoryPage({ page: current || 1, pageSize: pageSize || 10, ...rest });
          return {
            data: res.data,
            success: true,
            total: res.total,
          };
        }}
        rowKey="id"
        search={{ labelWidth: 'auto' }}
        toolBarRender={() => [
          <Button key="create" type="primary" onClick={handleCreate}>
            <PlusOutlined /> 新建
          </Button>,
        ]}
      />
      <Modal
        title={editingCategory ? '编辑分类' : '新建分类'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        destroyOnClose
      >
        <ProForm
          initialValues={editingCategory || {}}
          onFinish={handleFinish}
        >
          <ProFormText name="name" label="分类名称" rules={[{ required: true }]} />
          <ProFormSelect
            name="menuId"
            label="所属菜单"
            options={menus.map((menu) => ({ label: menu.name, value: menu.id }))}
            rules={[{ required: true, message: '请选择所属菜单' }]}
          />
        </ProForm>
      </Modal>
    </>
  );
};

export default CategoryPage;